<template>
    <div>
        <el-dialog
    class="dialog"
    v-model="dialogVisible"
    :title="type == 'add' ? '添加鲜花信息' :'修改鲜花信息'"
    width="30%"
    top="5vh"
    :before-close="handleClose"
  >
  <el-form :model="flowerForm" label-width="110px" :rules="flowerFormRules" ref="flowerFormref">
    <el-form-item label="鲜花名称" prop="name">
        <el-input  v-model="flowerForm.name"></el-input>
    </el-form-item>
    <el-form-item label="鲜花价钱" prop="price">
        <el-input  v-model="flowerForm.price"></el-input>
    </el-form-item>
    <el-form-item label="鲜花信息" prop="information">
        <el-input  v-model="flowerForm.information"></el-input>
    </el-form-item>
    <el-form-item label="鲜花种类" prop="type">
        <el-select 
            v-model="flowerForm.type" 
            :filterable="true"
            allow-create
            placeholder="请选择或输入鲜花种类" 
            style="width: 100%;">
            <!-- <el-option label="爱情鲜花" value="love" />
            <el-option label="友情鲜花" value="friend" />
            <el-option label="生日鲜花" value="birthday" />
            <el-option label="祝贺鲜花" value="congratulate" /> -->
            <el-option v-for="(item,index) in typeFlower" :label="item" :value="item" :key="index"/>
      </el-select>
    </el-form-item>
    <el-form-item label="鲜花库存" prop="inventory">
        <el-input  v-model="flowerForm.inventory"></el-input>
    </el-form-item>
    <el-form-item label="鲜花总销售量" prop="allSalesVolumes">
        <el-input  v-model="flowerForm.allSalesVolumes"></el-input>
    </el-form-item>
    <el-form-item label="是否热销" prop="hot">
        <el-select v-model="flowerForm.hot" placeholder="请选择是否热销" style="width: 100%;">
            <el-option label="热销" :value="true" />
            <el-option label="非热销" :value="false" />
      </el-select>
    </el-form-item>
    <el-form-item label="鲜花样式" prop="src">
        <el-upload
    class="avatar-uploader"
    action="/api/files/upload"
    :show-file-list="false"
    :on-success="handleAvatarSuccess"
    :before-upload="beforeAvatarUpload"
  >
    <img v-if="flowerForm.src" :src="flowerForm.src" class="avatar" />
    <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
  </el-upload>
  <!-- <el-input  v-model="flowerForm.src"></el-input> -->
    </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleCancle" >取消</el-button>
        <el-button type="primary" @click="handleConfirm">
          确认
        </el-button>
      </span>
    </template>
  </el-dialog>
    </div>
</template>

<script setup>
import { defineProps ,defineEmits,reactive,ref,onMounted,watch} from 'vue';
import {flowerType} from '@/api/flowers'
// 引入图标
import { Plus } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
// 接收父组件传值
const props = defineProps({
    dialogVisible:false, // 是否展示
    type:'', //弹框标题
    flowerFormInitial:{} //弹框默认信息
})
// 子传父的方法
const emits = defineEmits(['dialogShow','Confirm'])
// 弹框表单信息
const flowerForm = reactive({
    name:'',
    information:'',
    price:'',
    type:'',
    src:'',
    inventory:'', // 鲜花库存
    allSalesVolumes:0, //总销售量
    hot:false, //是否热销，默认为false
})
//创建ref
const flowerFormref = ref()
// 鲜花种类
const typeFlower = ref([])
// 库存校验规则
const inventoryRules = (rule, value, callback) => {
    // 只能输入正整数或0
    let reg =/^[0-9]*$/
    let res = reg.test(value);
    if (value.length === 0) {
    callback(new Error("库存为必填项"));
    }else{
        if(res){
        callback();
    }else{
        callback(new Error("只能输入正整数或0"))
        }
    }
    
}
// 总销量校验规则
const allSalesVolumesRules = (rule, value, callback) => {
    // 只能输入正整数或0
    let reg =/^[0-9]*$/
    let res = reg.test(value);
    if (value.length === 0) {
    callback(new Error("总销量为必填项"));
    }else{
        if(res){
        callback();
    }else{
        callback(new Error("只能输入正整数或0"))
        }
    }
    
}
// 价钱校验规则
const priceRules = (rule, value, callback) => {
    // 只能输入正整数或0
    let reg =/^\+?[1-9]\d*$/
    let res = reg.test(value);
    if (value.length === 0) {
    callback(new Error("价钱为必填项"));
    }else{
        if(res){
        callback();
    }else{
        callback(new Error("只能输入正整数且不能小于1"))
        }
    }
    
}
// 设置表单校验
const flowerFormRules = reactive({
    name:[
    {
      required: true,
      trigger: "blur",
      message: "鲜花名为必填项",
    },
    ],
    price:[
    {
      required: true,
      trigger: "blur",
      validator:priceRules
    },
    ],
    inventory:[
    {
      required: true,
      trigger: "blur",
      validator:inventoryRules
    },
    ],
    allSalesVolumes:[
    {
      required: true,
      trigger: "blur",
      validator:allSalesVolumesRules
    },
    ]
})
// 图片成功上传的函数
const handleAvatarSuccess = (response,uploadFile) => {
  // flowerForm.src = URL.createObjectURL(uploadFile.raw)
  flowerForm.src = response.filename
}
// 图片上传前的判断
const beforeAvatarUpload = (file) => {
    let types = ['image/jpeg','image/gif','image/bmp','image/png']
    const isImage = types.includes(file.type)
    const isLt1M = file.size / 1024 / 1024
    if(!isImage){
      ElMessage.error('上传图片只能是JPG/Jpeg/GIF/BMP/PNG格式！')
      return false
    }
    if (isLt1M > 2) {
      ElMessage.error('上传头像图片大小不能超过2MB')
        return false
    }
    return true
}
// 种类标签展示
// const typeFlower = (item) =>{
//     let type = ''
//     switch(item){
//         case 'love':
//             type = '爱情鲜花'
//             break
//         case 'friend':
//             type = '友情鲜花'
//             break
//         case 'birthday':
//             type = '生日鲜花'
//             break
//         case 'congratulate':
//             type = '祝贺鲜花'
//             break
//     }
//     return type
// }
// 点击关闭的回调函数
const handleClose = () => {
    emits('dialogShow',false)
}
// 点击取消的函数
const handleCancle = () =>{
    emits('dialogShow',false)
}
// 点击确认的函数
const handleConfirm = () =>{
    flowerFormref.value.validate(async (valid) => {
    if (!valid) return;
    // 向父组件中传值
    emits('dialogShow',false)
    emits('Confirm',flowerForm,props.type)
  });
}
onMounted(async()=>{
    if(props.type == 'revise'){
        // flowerForm = props.flowerFormInitial
        // 将信息进行赋值
        flowerForm.name = props.flowerFormInitial.name
        flowerForm.price = props.flowerFormInitial.price
        flowerForm.information = props.flowerFormInitial.information
        flowerForm.type = props.flowerFormInitial.type
        flowerForm.inventory = props.flowerFormInitial.inventory
        flowerForm.allSalesVolumes = props.flowerFormInitial.allSalesVolumes
        flowerForm.hot = props.flowerFormInitial.hot
        flowerForm.src = props.flowerFormInitial.src
        flowerForm._id = props.flowerFormInitial._id
        console.log(props.flowerFormInitial)
    }
    const data = await flowerType()
    typeFlower.value = data.typeData

})
</script>

<style lang="scss" scoped>
:deep(.el-dialog){
    border-radius: 15px;
}
:deep(.el-form){
    padding-right: 70px;
}
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
:deep(.el-upload) {
  border: 1px dashed #8c939d;
  border-radius: 6px;
  cursor: pointer;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
</style>